package com.cherry.androidcode.upload

import android.content.ContentResolver
import android.content.Context
import android.net.Uri
import android.provider.MediaStore
import okhttp3.MediaType
import okhttp3.MultipartBody
import okhttp3.RequestBody
import rxhttp.wrapper.utils.BuildUtil
import java.io.File
import java.io.FileNotFoundException

@JvmOverloads
fun Uri.asRequestBody1(
    context: Context,
    skipSize: Long = 0,
    mediaType: MediaType? = BuildUtil1.getMediaTypeByUri(context, this),
): RequestBody = UriRequestBody1(context, this, skipSize, mediaType)

@JvmOverloads
fun Uri.asPart1(
    context: Context,
    key: String,
    filename: String? = displayName(context),
    skipSize: Long = 0,
    contentType: MediaType? = BuildUtil.getMediaTypeByUri(context, this),
): MultipartBody.Part {
    return asRequestBody1(context, skipSize, contentType).let {
        OkHttpCompat1.createFormData(key, filename, it)
    }
}

internal fun Uri.displayName(context: Context): String? {
    if (scheme == ContentResolver.SCHEME_FILE) {
        return lastPathSegment
    }
    return getColumnValue(context.contentResolver, MediaStore.MediaColumns.DISPLAY_NAME)
}


internal fun Uri.getColumnValue(contentResolver: ContentResolver, columnName: String): String? {
    return contentResolver.query(
        this, arrayOf(columnName),
        null, null, null
    )?.use {
        if (it.moveToFirst()) it.getString(0) else null
    }
}


fun Uri?.length(context: Context): Long {
    return length(context.contentResolver)
}

//return The size of the media item, return -1 if does not exist, might block.
fun Uri?.length(contentResolver: ContentResolver): Long {
    if (this == null) return -1L
    if (scheme == ContentResolver.SCHEME_FILE) {
        return File(path).length()
    }
    return try {
        contentResolver.openFileDescriptor(this, "r").use { it?.statSize ?: -1 }
    } catch (e: FileNotFoundException) {
        -1L
    }
}

